import modelExtend from 'dva-model-extend'
import {
  bindUser,
  unbindUser,
  getUserIds,
} from './services/organization'
import { update, mine, detail } from './services/distributor'

import { listByUserIds as getUserByIds, listGroupByUserIds } from './services/user'
import { lwjPageModel } from 'utils/model'
import { getByField } from 'utils/helpers'
import { ROOT_ID } from 'utils/organizationConstant'
import { Modal, notification, message } from 'antd'

export default modelExtend(lwjPageModel, {
  namespace: 'userManage',

  state: {
    tree: [],
    currentItem: {},
    modalVisible: false,
    userIds: [],
    users: [],
    distributorUsers: [],
    lwjUsers: [],
    usersBackup: [],
    pageOptions: {
      sort: 'createTime',
      order: 'DESC'
    },
  },
  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(({ pathname }) => {
        /**
         * 列表页的监听
         */
        if (pathname === '/userManage') {
          dispatch({ type: 'getTree', payload: {} })
          // 清掉state中的树信息
          dispatch({ type: 'clear' })
        }
      })
    },
  },
  effects: {
    * getTree({ payload }, { call, put }) {
      const res = yield call(mine)

      let data = res.list.map(item => {
        item.parentId = 0
        return item
      }).sort((a, b) => a.name.localeCompare(b.name))

      yield put({ type: 'tree', payload: data })
    },

    * getDetail({ payload }, { call, put }) {
      const { id } = payload
      const res = yield call(detail, id)
      if (res.success) {
        yield put({ type: 'choose', payload: res.result })
      } else {
        message.error(res.message);
      }
    },

    * onChoose({ payload }, { call, put }) {
      const { organizationId } = payload
      if ('organizationId' in payload) {
        const res = yield call(getUserIds, organizationId)
        let userIds = res.result
        if (!res.success) {
          userIds = []
        }
        let params = {};
        params.userIds = userIds;
        params.name = payload.displayName;
        params.mobile = payload.mobile;
        const users = yield call(listGroupByUserIds, params)
        // 将用户绑到state上
        if (!_.isEmpty(users.result)) {
          yield put({
            type: 'bindUser', payload: {
              userIds: [],
              users: [...users.result.customerList,...users.result.staffList],
              distributorUsers: users.result.customerList,
              lwjUsers: users.result.staffList,
              usersBackup: users.result,
            }
          })
        }
      }
      yield put({ type: 'choose', payload: payload })
    },

    * onUpdate({ payload }, { call, put }) {
      const { id, datum } = payload
      const res = yield call(update, id, datum)
      if (res.success) {
        yield put({ type: 'hideModal' })
        yield put({ type: 'getTree' })
        yield put({ type: 'getDetail', payload: { id: id } })
      } else {
        message.error(res.message);
      }
    },

    * onSelectUser({ payload }, { call, put }) {
      yield put({ type: 'selectModal', payload: {} })
    },

    * onBindUser({ payload }, { call, put, select }) {
      const { id, ids } = payload
      const item = yield select(state => state.userManage.currentItem)
      const res = yield call(bindUser, { orgId: id, ids: ids })
      if (res.success) {
        yield put({ type: 'onChoose', payload: item })
        yield put({ type: 'hideModal' })
      } else {
        message.error(res.message);
      }
    },

    * onUnbindUser({ payload }, { call, put, select }) {
      const { id, ids } = payload
      const item = yield select(state => state.userManage.currentItem)
      const res = yield call(unbindUser, { orgId: id, ids: ids })
      if (res.success) {
        yield put({ type: 'onChoose', payload: item })
        notification.open({
          message: '成功',
          description: '解绑人员成功',
        })
      } else {
        throw res
      }
    },
  },
  reducers: {
    /**
     * 处理state中的tree
     * @param state
     * @param payload
     * @return {{}}
     */
    tree(state, { payload }) {
      if (Array.isArray(payload)) {
        let rootIndex = null
        for (let i = 0; i < payload.length; ++i) {
          if (payload[i].id === ROOT_ID) {
            rootIndex = i
          }
        }

        if (rootIndex !== null) {
          payload.splice(rootIndex, 1)
        }

      }

      state.tree = payload
      return {
        ...state
      }
    },

    clear(state, { payload }) {
      state.currentItem = {}
      state.parentItem = {}
      state.users = []
      state.userIds = []

      return {
        ...state
      }
    },

    /**
     * 选择
     * @param state
     * @param payload
     * @return {{}}
     */
    choose(state, { payload }) {
      state.currentItem = payload

      return {
        ...state
      }
    },

    bindUser(state, { payload }) {
      return {
        ...state,
        ...payload
      }
    },

    /**
     * 打开编辑的modal
     * @param state
     * @param payload
     * @return {{}}
     */
    edit(state, { payload }) {
      state.modalVisible = true

      return {
        ...state
      }
    },

    queryUserSuccess(state, { payload }) {
      return {
        ...state,
        userItems: payload.content,
        userPagination: {
          ...state.resourcePagination,
          current: payload.number + 1,
          total: payload.totalElements
        }
      }
    },

    selectModal(state, { payload }) {
      state.userSelectModalVisible = true
      return {
        ...state
      }
    },

    createSelectUserIds(state, { payload }) {
      state.userIds = payload

      return {
        ...state
      }
    },

    /**
     * 隐藏所有modal
     * @param state
     * @param payload
     * @return {{}}
     */
    hideModal(state, { payload }) {
      state.modalVisible = false
      state.userSelectModalVisible = false

      return {
        ...state
      }
    },

    searchUserList(state, { payload }) {
      // 搜索备份中的数据
      if (!_.isEmpty(payload)) {
        state.users = state.usersBackup.filter(item => {
          let bolt = false

          if ('displayName' in payload) {
            bolt = item.displayName.includes(payload.displayName)
            if (!bolt) {
              return bolt
            }
          }

          if ('mobile' in payload) {
            bolt = item.mobile.includes(payload.mobile)
            if (!bolt) {
              return bolt
            }
          }

          return bolt
        })
      } else {
        state.users = state.usersBackup
      }
      return {
        ...state
      }
    },
  },
})
